<template>
	<div class="grid-layout-container card">
		<el-dropdown v-show="globalStore.developerMode">
			<el-button class="module-add-btn" type="primary" plain :icon="Plus">添加组件</el-button>
			<template #dropdown>
				<el-dropdown-menu>
					<el-dropdown-item v-for="item in componentType" :key="item.value" @click="addGridItem(item)">
						{{ item.label }}
					</el-dropdown-item>
				</el-dropdown-menu>
			</template>
		</el-dropdown>
		<grid-layout
			v-model:layout="layouts"
			:col-num="4"
			:row-height="30"
			:is-draggable="true"
			:is-resizable="true"
			:is-mirrored="false"
			:vertical-compact="true"
			:margin="[10, 10]"
			:use-css-transforms="true"
			@layout-updated="saveLayout"
		>
			<grid-item class="card" v-for="item in layouts" :x="item.x" :y="item.y" :w="item.w" :h="item.h" :i="item.i" :key="item.i">
				<el-button-group size="small" style="float: right" v-if="globalStore.developerMode">
					<el-button type="primary" :icon="Delete" @click="removeGridItem" />
				</el-button-group>
			</grid-item>
		</grid-layout>
	</div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { GlobalStore } from "@/store";
import { componentType } from "@/assets/json/dict.json";
import { Delete, Plus } from "@element-plus/icons-vue";
import { nanoid } from "nanoid";

const globalStore = GlobalStore();

interface GridItemProps {
	x: number;
	y: number;
	w: number;
	h: number;
	i: string;
}
const layouts = ref<Array<GridItemProps>>([]);

const addGridItem = (item: { w: number; h: number }) => {
	const i = nanoid();
	layouts.value.push({
		x: 0,
		y: layouts.value.length * 6, // puts it at the bottom
		w: item.w,
		h: item.h,
		i
	});
	saveLayout();
};
const removeGridItem = (i: string) => {
	const index = layouts.value.findIndex(item => item.i === i);
	layouts.value.splice(index, 1);
	saveLayout();
};
const saveLayout = () => {
	console.log({
		menuId: "123",
		layouts: JSON.stringify(layouts.value)
	});
};
</script>

<style scoped lang="scss">
.grid-layout-container {
	height: 100%;
	.module-add-btn {
		margin-left: 10px;
		border-style: dashed;
	}
	.vue-grid-item {
		//color: var(--el-color-white);
		//border: 1px solid var(--el-color-primary);
	}
	.grid-item_btn {
		text-align: right;
	}
}
</style>
